﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System;
using System.Windows.Input;
using System.Threading;

namespace Akabana.Amf.Messaging.Command
{
    public class DelegateCommand : ICommand
    {
        private EventHandler CanExecuteChanged;

        event EventHandler ICommand.CanExecuteChanged
        {
            add
            {
                EventHandler handler2;
                EventHandler canExecuteChanged = this.CanExecuteChanged;
                do
                {
                    handler2 = canExecuteChanged;
                    EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, value);
                    canExecuteChanged = Interlocked.CompareExchange<EventHandler>(ref this.CanExecuteChanged, handler3, handler2);
                }
                while (canExecuteChanged != handler2);
            }
            remove
            {
                EventHandler handler2;
                EventHandler canExecuteChanged = this.CanExecuteChanged;
                do
                {
                    handler2 = canExecuteChanged;
                    EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, value);
                    canExecuteChanged = Interlocked.CompareExchange<EventHandler>(ref this.CanExecuteChanged, handler3, handler2);
                }
                while (canExecuteChanged != handler2);
            }
        }

        private Func<object, bool> canExecute;

        private Action<object> method;

        public DelegateCommand(Action<object> method)
            : this(method, null)
        {
        }

        public DelegateCommand(Action<object> method, Func<object, bool> canExecute)
        {
            this.method = method;
            this.canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            method.Invoke(parameter);
        }
    }
}
